/* eslint-disable eqeqeq */
/* eslint-disable prefer-promise-reject-errors */
/* eslint-disable no-undef */
import { Subject } from 'rxjs'
import config from '@/config/config'

const key = config.rongYun
const RC = RongIMLib.RongIMClient

export default {
  methods: {
    $RC_init () {
      return new Promise(resolve => {
        window.rongChatRoom = new Subject()
        window.rongChat = new Subject()
        RC.init(key)
        resolve()
      })
    },
    // 连接状态监听器
    $RC_setConnectionStatusListener (fn) {
      console.log('设置连接状态监听器')
      RC.setConnectionStatusListener({
        onChanged: function (status) {
          // 融云状态码文档： https://www.rongcloud.cn/docs/api/js/RongIMClient.js.html#line2569
          fn(status)
        }
      })
    },
    // 消息监听器
    $RC_setOnReceiveMessageListener () {
      console.log('设置消息监听器')

      RC.setOnReceiveMessageListener({
        onReceived: function (message) {
          // 融云消息文档： https://www.rongcloud.cn/docs/api/js/RongIMClient.js.html#line34
          // 融云消息来源类型：https://www.rongcloud.cn/docs/api/js/RongIMClient.js.html#line2622
          console.log('融云接受的信息:', message)

          if (message.messageType != 'TypingStatusMessage' && message.conversationType !== 4) {
            window.rongChat.next(message)
          }

          if (message.conversationType === 4) {
            // 聊天室监听消息内容
            window.rongChatRoom.next(message)
          }
        }
      })
    },

    // 获取会话列表
    $RC_getConversationList (conversationTypes = null) {
      // $RC_getConversationList (conversationTypes = [RongIMLib.ConversationType.PRIVATE, RongIMLib.ConversationType.SYSTEM]) {
      return new Promise(function (resolve, reject) {
        RongIMLib.RongIMClient.getInstance().getConversationList({
          onSuccess: function (list) {
            // list => 会话列表集合。
            console.log(list)
            resolve(list)
          },
          onError: function (error) {
            console.log(error)
            reject(error)
          }
        }, conversationTypes, 150)
      })
    },

    // 连接服务器
    $RC_connect (token) {
      return new Promise((resolve, reject) => {
        RC.connect(token, {
          onSuccess: function (userId) {
            resolve(userId)
          },
          onTokenIncorrect: function () {
            reject('token无效')
          },
          onError: function (errorCode) {
            let info = ''
            switch (errorCode) {
              case RongIMLib.ErrorCode.TIMEOUT:
                info = '超时'
                break
              case RongIMLib.ConnectionState.UNACCEPTABLE_PAROTOCOL_VERSION:
                info = '不可接受的协议版本'
                break
              case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
                info = 'appkey不正确'
                break
              case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
                info = '服务器不可用'
                break
              default:
                break
            }
            reject(info)
          }
        })
      })
    },
    // 重新连接
    $RC_reconnect () {
      return new Promise((resolve, reject) => {
        RC.reconnect({
          onSuccess: function (userId) {
            console.log(userId)
            resolve(userId)
          },
          onTokenIncorrect: function () {
            reject('token无效')
          },
          onError: function (errorCode) {
            reject(errorCode)
          }
        }, {
          // 默认 false, true 启用自动重连，启用则为必选参数
          auto: true,
          // 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒，可选
          url: 'https://cdn.ronghub.com/RongIMLib-2.3.5.min.js',
          // 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选
          rate: [100, 1000, 3000, 6000, 10000]
        })
      })
    },
    // 发送TextMessage快捷方式
    $RC_sendTextMessage (targetId, message, conversationType = RongIMLib.ConversationType.PRIVATE) {
      return new Promise(function (resolve, reject) {
        RC.getInstance().sendTextMessage(conversationType, targetId + '', message, {
          onSuccess: function (data) {
            console.log('发送信息成功回调：', data)
            // => data {messageUId:"消息唯一Id",timestamp:"发送消息时间戳"}
            resolve(data)
          },
          onError: function (errorcode) {
            reject(errorcode)
          }
        })
      })
    },
    // 发送消息
    $RC_sendMessage (targetId, msg, conversationType = RongIMLib.ConversationType.PRIVATE) {
      return new Promise(function (resolve, reject) {
        // eslint-disable-next-line space-in-parens
        RC.getInstance().sendMessage(conversationType, targetId + '', new RongIMLib.TextMessage( msg ), {
          onSuccess: function (message) {
            // message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
            resolve(message)
          },
          onError: function (errorCode, message) {
            console.log(errorCode, message)
            reject(errorCode)
          }
        })
      })
    },
    // 发送图片
    $RC_sendImage (targetId, msg, conversationType = RongIMLib.ConversationType.PRIVATE) {
      return new Promise(function (resolve, reject) {
        RC.getInstance().sendMessage(conversationType, targetId + '', new RongIMLib.ImageMessage(msg), {
          onSuccess: function (message) {
            // message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
            resolve(message)
          },
          onError: function (errorCode, message) {
            console.log(errorCode, message)
            reject(errorCode)
          }
        })
      })
    },
    // 清除指定用户未读消息数
    $RC_clearUnreadCount (targetId, conversationType = RongIMLib.ConversationType.PRIVATE) {
      return new Promise(function (resolve, reject) {
        RC.getInstance().clearUnreadCount(conversationType, targetId, {
          onSuccess: function () {
            // 清除未读消息成功。
            resolve()
          },
          onError: function (error) {
            // error => 清除未读消息数错误码。
            reject(error)
          }
        })
      })
    },
    // 加入聊天室
    $RC_joinChatRoom (roomId) {
      return new Promise((resolve, reject) => {
        RongIMLib.RongIMClient.getInstance().joinChatRoom(roomId, 10, {
          onSuccess: function () {
            // 加入聊天室成功。
            resolve()
          },
          onError: function (error) {
            // 加入聊天室失败
            reject(error)
          }
        })
      })
    },
    // 获取单聊历史记录
    // $RC_getHistoryMessages ({ targetId, count = 20, timestrap = null }) {
    //   return new Promise((resolve, reject) => {
    //     RC.getInstance().getHistoryMessages(RongIMLib.ConversationType.PRIVATE, targetId + '', timestrap, count, {
    //       onSuccess: function (list, hasMsg) {
    //         console.log(list, hasMsg)
    //         // list => Message 数组。
    //         // hasMsg => 是否还有历史消息可以获取。
    //         resolve(list, hasMsg)
    //       },
    //       onError: function (error) {
    //         console.log('GetHistoryMessages,errorcode:' + error)
    //         reject(error)
    //       }
    //     })
    //   })
    // },
    // 清除会话列表
    $RC_clearConversations () {
      return new Promise((resolve, reject) => {
        RC.getInstance().clearConversations({
          onSuccess: function () {
            // 清除会话成功
            resolve()
          },
          onError: function (error) {
            // error => 清除会话错误码
            reject(error)
          }
        })
      })
    },
    // 获取历史纪录
    $getRemoteHistoryMessages (conversationType, targetId, count = 7, pullMessageTime = null) {
      return new Promise((resolve, reject) => {
        RongIMLib.RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId + '', pullMessageTime, count, {
          onSuccess: function (list, hasMsg) {
            // list 历史消息数组，hasMsg为boolean值，如果为true则表示还有剩余历史消息可拉取，为false的话表示没有剩余历史消息可供拉取。
            resolve({
              list: list,
              hasMsg: hasMsg
            })
          },
          onError: function (error) {
            // getRemoteHistoryMessages error
            reject(error)
          }
        })
      })
    },
    // 退出聊天室
    $RC_quitChatRoom (chatRoomId) {
      return new Promise((resolve, reject) => {
        RongIMLib.RongIMClient.getInstance().quitChatRoom(chatRoomId, {
          onSuccess: function () {
            // 退出聊天室成功。
            resolve()
          },
          onError: function (error) {
            // 退出聊天室失败。
            reject(error)
          }
        })
      })
    },
    // 获取总未读数
    $RC_getTotalUnreadCount () {
      return new Promise((resolve, reject) => {
        RongIMClient.getInstance().getTotalUnreadCount({
          onSuccess: function (count) {
            console.log('获取所有会话未读消息数成功', count)
            resolve(count)
          },
          onError: function (error) {
            console.log('获取所有会话未读消息数失败', error)
            reject(error)
          }
        })
      })
    },
    // 获取会话
    $RC_getHistoryMessages (targetId) {
      return new Promise((resolve, reject) => {
        RongIMLib.RongIMClient.getInstance().getHistoryMessages(RongIMLib.ConversationType.PRIVATE, targetId, 0, 20, {
          onSuccess: function (list, hasMsg) {
            console.log('获取历史消息成功', list)
            resolve({ list, hasMsg })
          },
          onError: function (error) {
            // 请排查：单群聊消息云存储是否开通
            console.log('获取历史消息失败', error)
            reject(error)
          }
        })
      })
    }
  }
}
